package com.wangmei.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import unitTool.Dictionary;
import unitTool.JsonRsp;
import unitTool.JsonUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileUploadController {
    private final Logger logger = LoggerFactory.getLogger(FileUploadController.class);
    /**
     * 文件上传接口
     */
    @RequestMapping(value = "/upload", produces = MediaType.TEXT_PLAIN_VALUE)
    public String fileUpload(@RequestParam("file") MultipartFile uploadFile,
                                         HttpServletRequest request) throws JsonProcessingException {
        ObjectMapper objMapper = new ObjectMapper();
        //判断文件夹是否存在
        String fileUrl = request.getServletContext().getRealPath(Dictionary.FilePath.PROUDECT_PIC_PATH);
        logger.info(fileUrl);
        File dicitonary = new File(fileUrl);
        if (!dicitonary.exists()) {
            dicitonary.mkdir();
        }
        //组装文件名，判断文件是否为图片格式
        String filename = uploadFile.getOriginalFilename();
        if (!(filename.endsWith(".jpg") || filename.endsWith(".png") ||
                filename.endsWith(".jpeg") || filename.endsWith(".gif"))) {
            return objMapper.writeValueAsString(JsonUpload.fail("非图片文件(jpg、png、jpeg、gif)"));
        }
        //组装文件名，组装文件后缀
        String newFileName = getNewFileName(filename.substring(filename.lastIndexOf(".")));

        File newFile = new File(fileUrl+"/"+newFileName);
        String url = "/" + Dictionary.FilePath.PROUDECT_PIC_PATH + "/" + newFileName;
        try {
            //文件上床成功；
            uploadFile.transferTo(newFile);
            logger.info(url);
            return objMapper.writeValueAsString(JsonUpload.success(url));
        } catch (Exception e) {
            //文件上床失败
            e.printStackTrace();
            newFile.delete();
            return objMapper.writeValueAsString(JsonUpload.fail("系统错误，上传失败"));
        }

    }


    /**
     * 文件新名字为当前系统时间加上uuid中的前3位
     */
    public String getNewFileName(String fileType) {
        String newFileName = new Long(System.currentTimeMillis()).toString() + UUID.randomUUID().toString().substring(0, 3) + fileType;
        System.out.println("文件新名字" + newFileName);
        return newFileName;
    }

}
